package com.javasm.controller.ManageSystemController;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    /**
     * 上传路径
     */
    private String uploadPath = "D:\\logs\\files\\upload\\";

    /**
     * 下载路径
     */
    private String downloadPath = "D:\\logs\\files\\download\\";

    /**
     * 文件类型
     */
    private String[] fileTypeArray;

    /**
     * 文件大小
     */
    private int maxFileSize;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("请求到");
        //1.获取文件对象
        Part file = req.getPart("myfile");
        System.out.println("取到的文件"+file.getName());
        System.out.println("取到的文件2"+file.getSubmittedFileName());



        //文件上传路径
        String basePath = req.getServletContext().getRealPath("/");
        //上传的目录
        String folder = "img/";
        System.out.println(basePath+folder+file.getSubmittedFileName());

        //构建文件对象
        File filepng = new File(basePath+folder);
        //文件目录不存在则递归创建目录
        if (!filepng.exists()) {
            boolean mkdirs = filepng.mkdirs();
            if (!mkdirs) {
                throw new RuntimeException("创建文件夹失败");
            }
        }

        //2.临时文件存放到指定路径
        file.write(basePath+folder+file.getSubmittedFileName());

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        //3.接口响应路径给前台
        Map<String,Object> returnMap = new HashMap<String,Object>();
        returnMap.put("imgsrc","http://localhost:8080/"+folder+file.getSubmittedFileName());

        writer.print(JSON.toJSONString(returnMap));
        writer.flush();
        writer.close();
    }
}
